package com.opgea.crm.repository;

import java.util.ArrayList;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.opgea.crm.common.SetupsAttributeQualifier;
import com.opgea.crm.common.SetupsModuleQualifier;
import com.opgea.crm.domain.entities.SetupsValue;

@Repository
public class SetupsRepoImpl implements SetupsRepo{
	
	@PersistenceContext
	private EntityManager em;

	public void removeAttrValue(long attrValueid) {
		SetupsValue setupsValue=em.find(SetupsValue.class,attrValueid);
		em.remove(setupsValue);

	}

	public void saveAttrValue(SetupsValue setupsValue) {
		
		em.persist(setupsValue);
		
	}

	
	public List<SetupsValue> listSetupAttributes(
			SetupsModuleQualifier moduleName) {
		
		return listSetupValue(moduleName,null);
	}

	
	public List<SetupsValue> listSetupValue(SetupsModuleQualifier moduleName,
			SetupsAttributeQualifier attribName) {
	
		List<SetupsValue> list=new ArrayList<SetupsValue>();
		
		StringBuffer buffer=null;
		String cond=" WHERE ";
		if(moduleName!=null){
			buffer=new StringBuffer("SELECT new com.crm.domain.SetupsValue(entObj.id,entObj.fieldValue) FROM SetupsValue entObj");
			buffer.append(cond).append(" entObj.setupsModuleQualifier=:paramM");
			cond=" AND ";
		}
		if(buffer!=null && attribName!=null)
		{
			buffer.append(cond);
			buffer.append(" entObj.setupsAttributeQualifier=:paramA");
		}
		
		if(buffer!=null)
		{
			Query query=em.createQuery(buffer.toString());
			query.setParameter("paramM", moduleName);
			if(attribName!=null)
				query.setParameter("paramA", attribName);
			list=query.getResultList();
		}
		
		return list;
	}
	
	/*public List<SetupsValue> listSetupValue(SetupsModuleQualifier moduleName,
			SetupsAttributeQualifier attribName) {
	
		List<SetupsValue> list=new ArrayList<SetupsValue>();
		StringBuffer buffer=null;
		String cond=" WHERE ";
		if(moduleName!=null){
			buffer=new StringBuffer("SELECT new com.crm.domain.SetupsValue(entObj.id,entObj.fieldValue) FROM SetupsValue entObj");
			buffer.append(cond).append(" entObj.setupsModuleQualifier=:paramM");
			cond=" AND ";
		}
		if(buffer!=null && attribName!=null)
		{
			buffer.append(cond);
			buffer.append(" entObj.setupsAttributeQualifier=:paramA");
		}
		
		if(buffer!=null)
		{
			Query query=em.createQuery(buffer.toString());
			query.setParameter("paramM", moduleName);
			if(attribName!=null)
				query.setParameter("paramA", attribName);
			list=query.getResultList();
		}
		return list;
	}
*/
	
	public SetupsValue findById(long attrValueid) {
		
		return em.find(SetupsValue.class, attrValueid);
	}
	
	

	
}
